//
//  OpenSDK_QuickLoginView.m
//  OpenSDK
//
//  Created by 涂俊 on 2018/7/16.
//  Copyright © 2018年 WYHT. All rights reserved.
//

#import "OpenSDK_QuickLoginView.h"
#import "OpenSDK_PullDownView.h"
#import "OpenSDK_LoginMobileView.h"
#import "OpenSDK_LoginLoadingView.h"
#import "HistoryAccountCell.h"
#import "OpenSDK_Toast.h"
#import "OpenSDK_DataKeys.h"

#import "OpenSDK_UIManager.h"
#import "OpenSDK_LoginManager.h"
#import "OpenSDK_DataManager.h"
#import "OpenSDK_UIUtil.h"
#import "OpenSDK_AccountRecord.h"
#import "OpenSDK_LoginMoreView.h"
#import "OpenSDK_LoginMobileView.h"
#import "OpenSDK_LoginInvalidView.h"
#import "OPKTracking.h"
#import "OPKCoreConfiguration.h"
#import "OpenSDK_UIManager.h"

@interface OpenSDK_QuickLoginView ()<UITableViewDataSource, HistoryAccountCellDeleteDelegate>
@property(nonatomic, copy)NSArray *accounts;
@property(nonatomic, copy)OpenSDK_AccountRecord *selectedUser;
@end

@implementation OpenSDK_QuickLoginView

{
//    NSArray *accounts;
    OpenSDK_PullDownView *menuView;
}

static NSString *cellTag = @"HistoryAccountCell";

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _bgView.backgroundColor = UIColor.whiteColor;
    _bgView.layer.cornerRadius = 10;
    _bgView.layer.masksToBounds = true;
    
    // 如果指定logo图片，则设置对应logo图片
    NSString *logoImageName = [[[[NSBundle mainBundle] infoDictionary] objectForKey:OpenSDK_CONFIG] objectForKey:OpenSDK_LOGO];
    if (logoImageName != nil && logoImageName.length > 0) {
        // 如果没有指定logo图片，则使用默认logo图片
        UIImage *image = [UIImage imageNamed:logoImageName];
        if (image != nil) {
            [self.logoImgView setImage:image];
        }
    }
    
    _curAccountBg.layer.borderWidth = 0.5;
    _curAccountBg.layer.borderColor = [UIColor colorWithRed:160/255.0 green:160/255.0 blue:160/255.0 alpha:1].CGColor;
    _curAccountBg.layer.cornerRadius = 1;
    [_curAccountBg addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapHistory:)]];
    
    [[OPKTracking shared] pageView:OPKPageLoginQuick];
    
    OpenSDK_AccountRecord *current = [[OpenSDK_DataManager getInstance] getCurAccount];
    if (current) {
        // 显示上次登录账号
        [self setCurUser:current];
        
        //其他登录方式的显示
        [[OpenSDK_UIManager getInstance] handleOtherLoginTypesWithButton:self.otherButton curLoginType:@""];
    } else {
        [[OpenSDK_UIManager getInstance] closeUI];
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    [[OPKTracking shared] pageView:OPKPageLoginOther];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setCurUser:(OpenSDK_AccountRecord *)account {
    OpenSDK_AccountRecord *curUser = account;
    _selectedUser = curUser;
    if (curUser != nil) {
        NSString *userName = curUser.accountName;
        if (userName == nil  || [userName isEqual:@""]) {
            userName = curUser.accountValue;
        }
        self.curLoginAccountView.text = userName;
        switch (curUser.accountType) {
            case OpenSDKAccountTypeDynamic:
                self.curLoginTypeView.image = [UIImage imageNamed:@"op_icon_mobile"];
                break;
            case OpenSDKAccountTypeMobile:
                self.curLoginTypeView.image = [UIImage imageNamed:@"op_icon_mail"];
                break;
            case OpenSDKAccountTypeMail:
                self.curLoginTypeView.image = [UIImage imageNamed:@"op_icon_mail"];
                break;
            case OpenSDKAccountTypeGuest:
                self.curLoginTypeView.image = [UIImage imageNamed:@"op_icon_guest"];
                break;
            case OpenSDKAccountTypeOther:
                if ([curUser.platform isEqual:@"WeChatLogin"]) {
                    self.curLoginTypeView.image = [UIImage imageNamed:@"op_icon_wx"];
                } else if ([curUser.platform isEqual:@"AppleLogin"]) {
                    self.curLoginTypeView.image = [UIImage imageNamed:@"op_icon_apple"];
                } else if ([curUser.platform isEqual:@"QQ"]) {
                    self.curLoginTypeView.image = [UIImage imageNamed:@"op_icon_qq"];
                } else if ([curUser.platform isEqual:@"OneKey"]) {
                    self.curLoginTypeView.image = [UIImage imageNamed:@"op_icon_onekey"];
                } else {
                    self.curLoginTypeView.image = nil;
                }
                break; 
        }
    }
}

#pragma mark - lifeCycle
#pragma mark - delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [_accounts count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HistoryAccountCell *cell = [tableView dequeueReusableCellWithIdentifier:cellTag forIndexPath:indexPath];
    cell.account = [_accounts objectAtIndex:indexPath.row];
    cell.vc = self;
    cell.deleteDelegate = self;
    return cell;
}

// 删除账号记录
- (void)onDelete:(OpenSDK_AccountRecord *)account {
    
    // TODO 删除历史记录，弹出确认框
    if (menuView) {
        [menuView animateRemoveView];
    }
    
    [self deleteAccount:account];
}

- (void)deleteAccount:(OpenSDK_AccountRecord *)account {
    // 删除账号
    [[OpenSDK_DataManager getInstance] removeAccount:account];
    NSArray *accountList = [[OpenSDK_DataManager getInstance] getAccountList];
    if (accountList == nil || accountList.count == 0) {
        // 清除当前账号
        [[OpenSDK_DataManager getInstance] setCurAccount:nil];

        // 去默认登录
        [[OpenSDK_UIManager getInstance] showDefaultLoginView];
        [self popSelf];
        
    } else {
        // 判断是否为当前账号
        OpenSDK_AccountRecord *currentAccount = [[OpenSDK_DataManager getInstance] getCurAccount];
        if ([account isEqual:currentAccount]) {
            [[OpenSDK_DataManager getInstance] setCurAccount:accountList.firstObject];
            [self setCurUser:accountList.firstObject];
        } else if ([account isEqual:_selectedUser]) {   // 如果是选中账号
            [self setCurUser:accountList.firstObject];
        }
    }
}

- (void)popSelf {
    NSMutableArray *viewControllers = [self.navigationController.viewControllers mutableCopy];
    if (viewControllers.count > 1) {
        [viewControllers removeObjectAtIndex:0];
    }
    [self.navigationController setViewControllers:viewControllers.copy animated:NO];
}

#pragma mark - btn callback
- (IBAction)didClickLoginBtn:(id)sender {
    
    [[OPKTracking shared] event:OPKEventLoginQuickNext];
    
    OpenSDK_AccountRecord *curUser;
    if (_selectedUser != nil) {
        curUser = _selectedUser;
    } else {
        curUser = [[OpenSDK_DataManager getInstance] getCurAccount];
    }
    if (curUser == nil) {
        NSLog(@"当前没有选择账号，无法快捷登录");
        return;
    }
    
    // 先弹出loading框
    UIStoryboard *loginStoryboard = [UIStoryboard storyboardWithName:@"LoginMain" bundle:nil];
    OpenSDK_LoginLoadingView *vc = (OpenSDK_LoginLoadingView *) [loginStoryboard instantiateViewControllerWithIdentifier:@"OpenSDK_LoginLoadingView"];
    vc.accoutnName = curUser.accountName;
    [self.navigationController pushViewController:vc animated:NO];
    
    // 再调用登录接口
    [[OpenSDK_LoginManager getInstance] loginWithRecord:curUser delegate:^(BOOL result, OpenSDK_AccountRecord *account, long errorNo, NSString *err) {
        if (!result) {
            // 登录失败
            [[[OpenSDK_iToast makeText:err] setDuration:2000] show];
            if (errorNo == 1013) {
                // token失效错误码，直接跳转到手机登录，让用户重新登录一次
                [vc loginResultCallback:result account:account delegate:^{
                    [self invalidation:account];
                }];
                return;
            }
        }
        [vc loginResultCallback:result account:account];
    }];
}

// 账号失效
- (void)invalidation:(OpenSDK_AccountRecord *)account {
    // 删除账号
    [[OpenSDK_DataManager getInstance] removeAccount:account];
    NSArray *accountList = [[OpenSDK_DataManager getInstance] getAccountList];
    if (accountList == nil || accountList.count == 0) {
        // 清除当前账号
        [[OpenSDK_DataManager getInstance] setCurAccount:nil];
        // 如果当前账号是一键登录
        if (account.accountType == OpenSDKAccountTypeOther && [account.platform isEqual:OpenSDK_S_ONE_KEY] && [[OpenSDK_DataManager getInstance].supportLoginTypes containsObject:OpenSDK_S_ONE_KEY]) {
            [[OpenSDK_UIManager getInstance] showOneKeyLogin];
        } else {
            [[OpenSDK_UIManager getInstance] showMoboleViewControllerWithAccount:account canBack:NO];
        }
    } else {
        // 判断是否为当前账号
        OpenSDK_AccountRecord *currentAccount = [[OpenSDK_DataManager getInstance] getCurAccount];
        if ([account isEqual:currentAccount]) {
            [[OpenSDK_DataManager getInstance] setCurAccount:accountList.firstObject];
            [self setCurUser:accountList.firstObject];
        } else if ([account isEqual:_selectedUser]) {   // 如果是选中账号
            [self setCurUser:accountList.firstObject];
        }
        OpenSDK_LoginInvalidView *loginInvalidView = [[OpenSDK_LoginInvalidView alloc] init];
        loginInvalidView.complateBlock = ^(void){
            // 如果当前账号是一键登录
            if (account.accountType == OpenSDKAccountTypeOther && [account.platform isEqual:OpenSDK_S_ONE_KEY] && [[OpenSDK_DataManager getInstance].supportLoginTypes containsObject:OpenSDK_S_ONE_KEY]) {
                [[OpenSDK_UIManager getInstance] showOneKeyLogin];
            } else {
                [[OpenSDK_UIManager getInstance] showMoboleViewControllerWithAccount:account canBack:YES];
            }
        };
        [[OpenSDK_UIManager getInstance] showNextUIWithViewController:loginInvalidView];
        
    }
}

- (IBAction)didClickOtherLoginBtn:(id)sender {
    
    [[OpenSDK_UIManager getInstance] handleOtherLoginMethodWithCurLoginType:@"" contranctChecked:[OpenSDK_DataManager getInstance].contranctChecked];

//    UIStoryboard *loginStoryboard = [UIStoryboard storyboardWithName:@"LoginMain" bundle:nil];
//    OpenSDK_LoginMoreView *vc = (OpenSDK_LoginMoreView *) [loginStoryboard instantiateViewControllerWithIdentifier:@"OpenSDK_LoginMoreView"];
//    [self.navigationController pushViewController:vc animated:NO];
}

- (void)tapHistory:(UITapGestureRecognizer *)tap {
    [self didClickHistoryBtn:self.historyBtn];
}
- (IBAction)didClickHistoryBtn:(id)sender {
    _accounts = [[OpenSDK_DataManager getInstance] getAccountList];
    // 当前用户放入下拉列表
    // 其他登录方式登录
    UIButton *dloginBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 0, 24)];
    [dloginBtn setImage:[UIImage imageNamed:@"op_icon_account_history_add"] forState:UIControlStateNormal];
    [dloginBtn setTitle:@"添加新账号" forState:UIControlStateNormal];
    [dloginBtn setTitleColor:[UIColor colorWithRed:140/255.0 green:140/255.0 blue:140/255.0 alpha:1] forState:UIControlStateNormal];
    dloginBtn.titleLabel.font = [UIFont systemFontOfSize:10];
    [dloginBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 6, 0, 0)];
    [dloginBtn setContentEdgeInsets:UIEdgeInsetsMake(0, -80, 0, 0)];
    [dloginBtn addTarget:self action:@selector(loginWithOtherType) forControlEvents:UIControlEventTouchUpInside];
    
    menuView = [OpenSDK_PullDownView pullMenuAnchorView:sender
                                          tableDelegate:self
                                              menuWidth:self.curAccountBg.frame.size.width
                                            cellNibName:@"HistoryAccountCell"
                                    cellReuseIdentifier:@"HistoryAccountCell"];
    menuView.additionalView = dloginBtn;
    menuView.additionalViewHeight = dloginBtn.frame.size.height;
    menuView.menuCellHeight = self.curAccountBg.frame.size.height;
    menuView.menuMaxHeight = 2 * self.curAccountBg.frame.size.height + dloginBtn.frame.size.height;//默认显示3格
    menuView.place = AnchorPlaceRight;
    
    __weak typeof(self) weakSelf = self;
    menuView.blockSelectedMenu = ^(NSInteger menuRow) {
        // 点击历史账号
        [weakSelf setCurUser:[weakSelf.accounts objectAtIndex:menuRow]];
    };
    menuView.blockClose = ^{
        [weakSelf.otherButton setHidden:NO];
    };
    
    [menuView show:YES];
    [_otherButton setHidden:YES];
}

- (IBAction)didClickCloseBtn:(id)sender {
    //    [self dismissViewControllerAnimated:NO completion:nil];
    [[OpenSDK_UIManager getInstance] closeUI];
    [[OpenSDK_LoginManager getInstance] sendLoginCacelEvent];
}

- (void)loginWithOtherType {
    [menuView animateRemoveView];
    [_otherButton setHidden:NO];
    // 手机验证码登录
    [[OpenSDK_UIManager getInstance] showViewControllerWithSBId:@"LoginMain" vcid:@"OpenSDK_LoginMobileView"];
}

@end
